package cn.seapon.talker.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;
import android.util.Log;
import cn.seapon.talker.common.ChatMsgEntity;
import cn.seapon.talker.common.LoginRequestEntity;
import cn.seapon.talker.common.MessageContent;
import cn.seapon.talker.common.MessageGenre;
import cn.seapon.talker.common.TMessage;
import cn.seapon.talker.exception.AccountOrPasswdIsNullException;
import cn.seapon.talker.infocarrier.NewVersionInfos;
import cn.seapon.talker.infocarrier.SharedItems;
import cn.seapon.talker.infocarrier.TalkerConfig;
import cn.seapon.talker.utils.StreamTools;

/** 
 * @author 作者 E-mail: 
 * @version 创建时间：2015年1月4日 下午7:51:37 
 * 类说明 
 */
public class TalkerNetOperationUtils {
	private static final String TAG = "||__TalkerNetOperationUtils__||";
	
	public static void socketConnect() throws IOException{
		SharedItems.socket = new Socket();
		SocketAddress endpoint = new InetSocketAddress(
				SharedItems.SERVER_HOST_IP, 38542);
		//阻塞 3秒超时
		SharedItems.socket.connect(endpoint, 3000);
	}
	
	/**
	 * 登录请求
	 * @param account 登录账户名
	 * @param passwd 加密后的密码
	 * @return TRUE 登录成功  FALSE 登录失败
	 * @throws IOException 
	 * @throws UnsupportedEncodingException 
	 * @throws JSONException 
	 * @throws AccountOrPasswdIsNullException 
	 */
	public static boolean loginCheck(String account ,String passwd) throws UnsupportedEncodingException, IOException, JSONException {
		TalkerNetOperationUtils.socketConnect();
		if (TextUtils.isEmpty(account) || TextUtils.isEmpty(passwd)) {
			return false;
		}
		TMessage tm = new TMessage();
		tm.setSenderId(account);
		tm.setSendTime(System.currentTimeMillis());
		tm.setGenre(MessageGenre.LOGIN_REQUEST);
		LoginRequestEntity entity = new LoginRequestEntity();
		entity.setAccount(account);
		entity.setPasswd(passwd);
		MessageContent content = new MessageContent();
		content.setLoginEntity(entity);
		tm.setContent(content);

		System.out.println("__写入数据为："+tm.getJSonString());
		if (SocketUtils.writeStringToSocket(SharedItems.socket, tm.getJSonString())) {
			String line = SocketUtils.readStringFromSocket(SharedItems.socket);

			Log.d(TAG, "登录返回的数据是："+line);
			JSONObject json = new JSONObject(line);
			TMessage messagRet = TMessage.getObjectFromJson(json);
			//登录结果
			boolean resultCode = messagRet.getContent().getResultCode();

			if (resultCode == true) {
				SharedItems.friendListInfomation = messagRet.getContent().getFriendInfos();
				SharedItems.groupInfo = messagRet.getContent().getGroupInfo();
				ChatMsgEntity[] unreads = messagRet.getContent().getUnreads();
				for (int i = 0; i < unreads.length; i++) {
					SharedItems.add(unreads[i]);
				}
				SharedItems.userInformation = messagRet.getContent().getUserInfo();
				return true;
			}
		}
		return false;
		
	}

	public static void checkUpdate() throws IOException, JSONException {
		URL url = new URL(TalkerConfig.UPDATE_CHECK_URL);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");// 大写
		conn.setConnectTimeout(2000);
		// 获取响应码 阻塞时方法
		int code = conn.getResponseCode();
		if (code == 200) {
			// 联网成功
			InputStream is = conn.getInputStream();// 获取输入流
			// 把流转成String 使用StreamTools
			String result = StreamTools.readFromStream(is);
			Log.i(TAG, "联网成功了" + result);
			// json解析 JSONObject(String str)
			JSONObject obj = new JSONObject(result);// 会抛出异常
			// 得到服务器的版本信息
			SharedItems.newVersionInfos = new NewVersionInfos(
					obj.getInt("versionCode"),
					(String) obj.get("versionName"),
					(String) obj.get("address"),
					(String) obj.get("describe"));
		}
	}
	
	
}
